package cn.jdy.plugins.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.platform.entity.News;
import cn.jdy.platform.service.NewsService;
import cn.jdy.plugins.entity.Attachment;
import cn.jdy.plugins.entity.Company;
import cn.jdy.plugins.entity.CompanyContext;
import cn.jdy.plugins.entity.Member;
import cn.jdy.plugins.service.AttachmentService;
import cn.jdy.plugins.service.CompanyContextService;
import cn.jdy.plugins.service.CompanyService;
import cn.jdy.plugins.service.MemberService;

/**
 * 企业申请展示内容操作类
 *
 * @author GXP
 */
@Controller
@RequestMapping("/companyContext")
public class CompanyContextCtrl extends BaseCtrl {
	@Autowired
	private CompanyContextService companyContextService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private AttachmentService attachmentService;
	@Autowired
  private NewsService newsService; 
  @Autowired
  private MemberService memberService;

	/**
	 * 保存企业展示信息
	 *
	 * @param context
	 * @param myfiles
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/saveBrandDetail", method = RequestMethod.POST)
	public ModelAndView saveBrandDetail(CompanyContext context, @RequestParam(required = false)String[] attaId, @RequestParam(required = false) MultipartFile[] myfiles, @RequestParam(required = false) MultipartFile brandLogoFile, @RequestParam(required = false) MultipartFile companyLogoFile, HttpServletRequest request) throws IOException {
	  //    ModelAndView mv = new ModelAndView();
		// 如果只是上传一个文件，则只需要MultipartFile类型接收文件即可，而且无需显式指定@RequestParam注解
		// 如果想上传多个文件，那么这里就要用MultipartFile[]类型来接收文件，并且还要指定@RequestParam注解
		// 并且上传多个文件时，前台表单中的所有<input
		// type="file"/>的name都应该是myfiles，否则参数里的myfiles无法获取到所有上传的文件
		// 暂时修改为直接通过审核，后期添加审核验证
	  ModelAndView mv = new ModelAndView("redirect:/companyContext/rediradd");
		try {
			//context.setState(1);
			context.setCreateDate(DateUtil.getCurrentDate2());
			String path = request.getSession().getServletContext().getRealPath("/");
			companyContextService.addCompanyContext(context, attaId, myfiles, brandLogoFile, companyLogoFile, path, request);
			mv.addObject("msg", "提交成功");
		} catch (Exception e) {
			mv.addObject("msg", "提交失败");
			BaseLog.e(this.getClass(), "saveBrandDetail 保存企业展示信息失败", e);
		}
		return mv;
	}

	@RequestMapping("/queryCompanyContext")
	@ResponseBody
	public Map<String, Object> queryCompanyContext(Integer companyId) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("count", companyContextService.find("companyId", companyId));
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "queryCompanyContext 查询企业展示信息失败", e);
		}
		
		return jsonMap;
	}

	/**
	 * 跳转企业申请展示页面
	 *
	 * @return
	 */
	@RequestMapping("/rediradd")
	public ModelAndView redirAdd(String msg) {
		ModelAndView mv = new ModelAndView("/company/applyshow.jsp");
		try {
		  Member member_old = (Member)session.getAttribute("user");
			Member member = memberService.find(member_old.getId());
			mv.addObject("member", member);
			if(msg!=null) mv.addObject("msg", msg);
			CompanyContext context = companyContextService.findOne("companyId", member.getCompany().getId());
			if(null != context) {
				List<Attachment> list = attachmentService.findAllAttachmentByBrandId(context.getId());
				mv.addObject("context", context);
				if(list!=null && list.size()>0)
					mv.addObject("attachment", list);
			}

		} catch (Exception e) {
			BaseLog.e(this.getClass(), "redirAdd 跳转企业申请展示页面失败", e);
		}
		
		return mv;
	}
	/**
	 * 品牌展示页面首页
	 * @return
	 */
	@RequestMapping("/index/{companyId}")
	public ModelAndView index(@PathVariable("companyId") Integer companyId,String view){
	  ModelAndView mv = new ModelAndView();
	  try {
		  Company company = companyService.findOne("id", companyId);
		  CompanyContext context = companyContextService.findOne("companyId", companyId);
//		  if(context != null && company != null){
		    mv.addObject("company", company);
		    mv.addObject("context", context);
		    mv.setViewName("/company/index.jsp");
		    mv.addObject("view",view);
//		  }else{
//		    mv.setViewName("500.jsp");
//		  }
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "index 品牌展示页面首页失败", e);
		}
	  
	  return mv;
	}
	
	/**
	 * 品牌介绍展示页面
	 * @return
	 */
	@RequestMapping("/brandetail/{companyId}")
	public ModelAndView brandDetail(@PathVariable("companyId") Integer companyId,String view){
	  ModelAndView mv = new ModelAndView();
	  try {
		  Company company = companyService.findOne("id", companyId);
		    CompanyContext context = companyContextService.findOne("companyId", companyId);
		    if(context != null || company != null){
		      mv.addObject("company", company);
		      mv.addObject("context", context);
		      mv.setViewName("/company/brandetail.jsp");
		      mv.addObject("view",view);
		    }else{
		      mv.setViewName("500.jsp");
		    }
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "brandDetail 品牌介绍展示页面失败", e);
		}
	  
	  return mv;
	}
	
	/**
	 * 招商政策说明
	 * @return
	 */
	@RequestMapping("/roledetail/{companyId}")
  public ModelAndView roledetail(@PathVariable("companyId") Integer companyId,String view){
    ModelAndView mv = new ModelAndView();
    try {
    	Company company = companyService.findOne("id", companyId);
        CompanyContext context = companyContextService.findOne("companyId", companyId);
        if(context != null || company != null){
          mv.addObject("company", company);
          mv.addObject("context", context);
          mv.setViewName("/company/roledetail.jsp");
          mv.addObject("view",view);
        }else{
          mv.setViewName("500.jsp");
        }
	} catch (Exception e) {
		 mv.setViewName("500.jsp");
		BaseLog.e(this.getClass(), "brandDetail 品牌介绍展示页面失败", e);
	}
    return mv;
  }
	
	/**
   * 信誉认证
   * @return
   */
  @RequestMapping("/credit/{companyId}")
  public ModelAndView credit(@PathVariable("companyId") Integer companyId,String view){
    ModelAndView mv = new ModelAndView();
    try {
    	Company company = companyService.findOne("id", companyId);
        CompanyContext context = companyContextService.findOne("companyId", companyId);
//        if(context != null || company != null){
          mv.addObject("company", company);
          mv.addObject("context", context);

          List<Attachment> attchs = attachmentService.findAttachmentByBrandId(context.getId());
          mv.addObject("attchments", attchs);
          mv.setViewName("/company/credit.jsp");
          mv.addObject("view",view);
//        }else{
//          mv.setViewName("500.jsp");
//        }
	} catch (Exception e) {
		 mv.setViewName("500.jsp");
		BaseLog.e(this.getClass(), "credit 信誉认证失败", e);
	}
    
    return mv;
  }
  
  /**
   * 发布内容读取
   * @return
   */
  @RequestMapping("/t-{type}/{companyId}")
  public ModelAndView context(@PathVariable("type") Integer type,@PathVariable("companyId") Integer companyId,String view){
    ModelAndView mv = new ModelAndView();
    try {
        Company company = companyService.findOne("id", companyId);
        CompanyContext context = companyContextService.findOne("companyId", companyId);
        
        if(type == 1){
          mv.addObject("typename", "企业介绍");
        }else if(type == 2){
          mv.addObject("typename", "产品展示");
        }else if(type == 3){
          mv.addObject("typename", "招聘信息");
        }else if(type == 4){
          mv.addObject("typename", "联系我们");
        }
        
        if(company == null){
          mv.setViewName("404.jsp");
        }else if(context == null){
          mv.addObject("company", company);
          mv.addObject("noinput", true);// 是否已录入信息
          mv.setViewName("/company/contentshow.jsp");
          mv.addObject("view",view);
        }else{
          if(type == 1){
            mv.addObject("typename", "企业介绍");
            mv.addObject("context", context.getHomePageContext());
          }else if(type == 2){
            mv.addObject("typename", "产品展示");
            mv.addObject("context", context.getBrandIntroduction());
          }else if(type == 3){
            mv.addObject("typename", "招聘信息");
            mv.addObject("context", context.getInvestmentPolicy());
          }else if(type == 4){
            mv.addObject("typename", "联系我们");
            mv.addObject("context", context.getContentus());
          }
          mv.addObject("company", company);
          mv.setViewName("/company/contentshow.jsp");
          mv.addObject("view",view);
        }
  } catch (Exception e) {
     mv.setViewName("500.jsp");
    BaseLog.e(this.getClass(), "发布内容读取展示页面失败", e);
  }
    return mv;
  }
  
  /**
   * 企业用户的新闻列表读取
   * @return
   */
  @RequestMapping("/news-{type}/{companyId}/{columnId}")
  public ModelAndView news(News news,@PathVariable("type") Integer type,@PathVariable("companyId") Integer companyId,@PathVariable("columnId") Long columnId,String view,Integer pageNo,Integer pageSize){
    ModelAndView mv = new ModelAndView();
    if(pageNo==null) pageNo = 1;
    if(pageSize==null)pageSize = 5;
    Long count = 0L;
    String userid = "";
    try {
      Company company = new Company();
      company.setId(companyId);
      Member member = memberService.findOne("company",company);
      if(member != null){
        userid = member.getId();
      }
       
      news.setColumnId(columnId);
      news.setUserid(userid);
      news.setiDisplayStart((pageNo - 1) * pageSize);//查询起始值
      news.setiDisplayLength(pageSize);//查询条数
      count = newsService.count(news);
      List<News> dataList = newsService.query(news);
      mv.addObject("column", this.confService.queryByType(GlobalConstant.TYPE_NEWS, 9667L));
      mv.addObject("company", member.getCompany());
      mv.addObject("companyId", companyId);
      mv.addObject("columnId", columnId);
      mv.addObject("type", type);
      mv.addObject("pageNo", news.getPageNo());
      mv.addObject("size", pageSize);
      mv.addObject("total", count);
      mv.addObject("dataList", dataList);
      mv.setViewName("/company/companynews.jsp");
      mv.addObject("view",view);
    } catch (Exception e) {
      mv.setViewName("500.jsp");
      BaseLog.e(this.getClass(), "发布内容读取展示页面失败", e);
    }
    return mv;
  }
  
  
  /**
   * 加入我们
   * @return
   */
  @RequestMapping("/join")
  public ModelAndView join(){
    ModelAndView mv = new ModelAndView("/company/join.jsp");
    return mv;
  }
  
  /**
   * 中小企业资料库
   * @return
   */
  @RequestMapping("/infolist")
  public ModelAndView infolist(){
    ModelAndView mv = new ModelAndView("/company/infolist.jsp");
    return mv;
  }
  
  /**
   * 风险预警
   * @return
   */
  @RequestMapping("/cancelauth")
  public ModelAndView cancelauth(){
    ModelAndView mv = new ModelAndView("/company/cancelauth.jsp");
    return mv;
  }
  
  
}
